# -*- coding: utf-8 -*-

from datetime import date, timedelta

from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import GoodsVisitCount
from meiduo_admin.serializers.increment import GoodsSerializer
from users.models import User


class UserTotalCountView(APIView):
    '''
    用户总量统计
    '''

    # 指定管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前日期
        now_date = date.today()
        # 获取所有用户总数
        count = User.objects.all().count()
        return Response({
            'count': count,
            'date': now_date
        })

class UserDayCountView(APIView):
    '''
    日增用户统计
    '''

    # 指定管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前日期
        now_date = date.today()
        count = User.objects.filter(date_joined__gte=now_date).count()
        return Response({
            'count': count,
            'date': now_date
        })


class UserActiveCountView(APIView):
    '''
    日活用户统计
    '''

    # 指定管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前日期
        now_date = date.today()
        count = User.objects.filter(last_login__gte=now_date).count()
        return Response({
            'count': count,
            'date': now_date
        })


class UserOrderCountView(APIView):
    '''
    日下单用户量统计
    '''

    # 指定管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_date = date.today()
        count = User.objects.filter(orders__create_time__gte=now_date).count()
        return Response({
            'count': count,
            'date': now_date
        })


class UserMonthCountView(APIView):
    '''
    月增用户统计
    '''

    # 指定管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_date = date.today()
        start_date = now_date - timedelta(29)
        date_list = []

        for i in range(30):
            index_date = start_date + timedelta(days=i)
            cur_date = start_date + timedelta(days=i + 1)
            count = User.objects.filter(date_joined__gte=index_date, date_joined__lt=cur_date).count()
            date_list.append({
                'count': count,
                'date': index_date
            })

        return Response(date_list)


class GoodsDayView(APIView):
    '''
    日分类商品访问量
    '''
    def get(self, request):
        now_date = date.today()
        data = GoodsVisitCount.objects.filter(date=now_date)
        # 序列化返回分类数量
        ser = GoodsSerializer(data, many=True)
        return Response(ser.data)
